package com.wyt.common.socket.websocket;

import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;
import java.nio.ByteBuffer;

public class MyWebSocketClient {

    public static WebSocketClient getWsClient() throws Exception {
        WebSocketClient webSocketClient = new WebSocketClient(new URI("ws://127.0.0.1:8098/sendCmd/cfae4fae-18a7-4697-944c-2bf7012ca1ca")) {
            @Override
            public void onOpen(ServerHandshake serverHandshake) {
                System.out.println("建立链接");
            }

            @Override
            public void onMessage(String s) {
                System.out.println("接收消息：" + s);
            }

            @Override
            public void onMessage(ByteBuffer bytes) {
                System.out.println("byte len:" + bytes.array().length);
            }

            @Override
            public void onClose(int i, String s, boolean b) {
                System.out.println("关闭客户端");
            }

            @Override
            public void onError(Exception e) {
                throw new RuntimeException(e);
            }
        };
        webSocketClient.connect();
        return webSocketClient;
    }

    public static void main(String[] args) {
        try {
            System.out.println(123);

            new Thread(() -> {
                try {
                    WebSocketClient wsClient = MyWebSocketClient.getWsClient();
                    while (!wsClient.isOpen()) {
                        System.out.println(1);
                        Thread.sleep(1000);
                    }
                    System.out.println("链接成功.....");
//                    wsClient.send("1111123455");
                    wsClient.send("{\"deviceId\":\"cfae4fae-18a7-4697-944c-2bf7012ca1ca\",\"type\":\"take_off\",\"commandID\":\"qwe\"}");
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }).start();

            Thread.sleep(1000 * 300);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        System.out.println("finish");
    }

}
